package advance.x000.acw_95;


import java.util.Arrays;
import java.util.Scanner;


public class Main {
    public static int N = 6;
    public static char[] s = new char[N - 1];
    public static int[] a;
    public static int[] aa = new int[N];
    public static int ans;


    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // 5X5 组数
        int n = scanner.nextInt();
        while (n-- != 0) {
            a = new int[N];
            aa = new int[N];
            for (int i = 1; i <= 5; i++) {
                s = scanner.next().toCharArray();
                for (int j = 0; j < 5; j++) {
                    a[i] = a[i] * 2 + (s[j] - '0');
                }
            }
            ans = 7;
            for (int p = 0; p < (1 << 5); p++) clac(p);
            if (ans == 7) {
                System.out.println(-1);
            } else {
            System.out.println(ans);
            }
        }
    }

    public static void clac(int p) {
        aa = Arrays.copyOf(a, 6);
        int k = 0;
        // 根据第一行点击方案p执行点击
        for (int y = 0; y < 5; y++) {
            if (!(((p >> y) & 1) == 1)) {
                turn(1, y);
                if (++k > ans) return;
            }
        }
        // printLamp();
        // 再从第一行到第四行，遇领按下一行同列按钮
        for (int x = 1; x < 5; x++) {
            for (int y = 0; y < 5; y++) {
                if (!(((aa[x] >> y) & 1) == 1)) {
                    turn(x + 1, y);
                    if (++k > ans) return;
                }
            }
        }
        // printLamp();
        if (aa[5] == 31) ans = k;

    }

    static void turn(int x, int y) {
        aa[x] ^= 1 << y;
        if (x != 1) aa[x - 1] ^= 1 << y;
        if (x != 5) aa[x + 1] ^= 1 << y;
        if (y != 0) aa[x] ^= 1 << (y - 1);
        if (y != 4) aa[x] ^= 1 << (y + 1);
    }

    public static void printLamp() {
        for (int i = 1; i <= 5; i++) {
            for (int j = 0; j < 5; j++) {
                System.out.print((int) ((aa[i] >> j) & 1) + " ");
            }
            System.out.println();
        }
    }

}
